﻿//1004.最大连续1的个数III
class Solution {
public:
    int longestOnes(vector<int>& nums, int k) {
        int sum = 0, size = nums.size(), len = 0;
        for (int left = 0, right = 0; right < size; right++)
        {
            if (nums[right] == 0)
            {
                sum++;
            }

            while (sum > k)
            {
                if (nums[left] == 0)
                {
                    sum--;
                }
                left++;
            }

            if (right - left + 1 > len)
            {
                len = right - left + 1;
            }
        }
        return len;
    }
};

//1658.将x减到0的最小操作数
class Solution {
public:
    int minOperations(vector<int>& nums, int x) {
        int target = 0, size = nums.size();
        for (int i = 0; i < size; i++)
        {
            target += nums[i];
        }
        target -= x;
        if (target < 0)
        {
            return -1;
        }
        if (target == 0)
        {
            return size;
        }

        int sum = 0, len = -1;
        for (int left = 0, right = 0; right < size; right++)
        {
            sum += nums[right];

            while (sum > target)
            {
                sum -= nums[left++];
            }

            if (sum == target)
            {
                len = max(len, right - left + 1);
            }
        }
        return len == -1 ? -1 : size - len;
    }
};

//904.水果成栏
class Solution {
public:
    int totalFruit(vector<int>& fruits) {

        int hash[100001] = { 0 };
        int size = fruits.size(), len = 0;

        for (int left = 0, right = 0, count = 0; right < size; right++)
        {
            if (hash[fruits[right]]++ == 0)
            {
                count++;
            }

            while (count > 2)
            {
                hash[fruits[left]]--;
                if (hash[fruits[left]] == 0)
                {
                    count--;
                }
                left++;
            }

            len = max(len, right - left + 1);
        }
        return len;
    }
};